<?php
namespace lib\wxbiz;

use lib\wxbiz\aes\wxbizMsgCrypt;
use lib\wxbiz\WechatRequest;

class Wechat
{

    private $request;

    public function __construct($agent_id)
    {
        // 接口调试
        if (isset($_GET['echostr'])) {
            $token = WechatCache::getToken($agent_id);
            $encodingAesKey = WechatCache::getEncodingAesKey($agent_id);
            $corpId = WechatCache::getCorpId($agent_id);
            $this->validateSignature($token, $encodingAesKey, $corpId);
        }
        // 是否打印错误报告
        // $this->debug = $debug;
        if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
            // 接受并解析微信中心POST发送XML数据
            $xml = (array) simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA'], 'SimpleXMLElement', LIBXML_NOCDATA);
            $content = $GLOBALS['HTTP_RAW_POST_DATA'];
            // 将数组键名转换为小写
            $this->request = array_change_key_case($xml, CASE_LOWER);
        } else {
            $this->request = array();
            $content = '无数据';
        }
        $this->run();
    }

    public function run()
    {
        return WechatRequest::switchType($this->request);
    }

    public function validateSignature($token, $encodingAesKey, $corpId)
    {
        $sVerifyMsgSig = urldecode($_GET['msg_signature']);
        $sVerifyTimeStamp = urldecode($_GET['timestamp']);
        $sVerifyNonce = urldecode($_GET['nonce']);
        $sVerifyEchoStr = $_GET['echostr'];
        
        // 需要返回的明文
        $sEchoStr = "";
        $wxcpt = new wxbizMsgCrypt($token, $encodingAesKey, $corpId);
        $errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
        if ($errCode == 0) {
            // 验证URL成功，将sEchoStr返回
            echo $sEchoStr;
        } else {
            echo "ERR: " . $errCode . "\n\n'";
        }
        exit();
    }
}